package com.hiup.utils;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * http请求工具类
 *
 * @author YFC
 * @create 2018-12-21 上午 1:17
 */
public class HttpUtils {
    private static Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 发送Http post请求
     *
     * @param xmlInfo json转化成的字符串
     * @param url     请求url
     * @return 返回信息
     */
    public static String doHttpPost(String xmlInfo, String url) {
        log.info("xmlInfo is {},url is {}", xmlInfo, url);
        byte[] xmlData = xmlInfo.getBytes();
        InputStream instr = null;
        java.io.ByteArrayOutputStream out = null;
        try {
            java.net.URL conn_url = new URL(url);
            URLConnection urlCon = conn_url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setRequestProperty("content-Type", "application/json");
            urlCon.setRequestProperty("charset", "utf-8");
            urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            instr = urlCon.getInputStream();
            byte[] bis = IOUtils.toByteArray(instr);
            String responseString = new String(bis, "UTF-8");
            if ((responseString == null) || ("".equals(responseString.trim()))) {
                log.error("The data is empty!!!");
            }
            log.info("The return data is {}", responseString);
            return responseString;
        } catch (Exception e) {
            log.error("Return data exception is {},{}", e.getMessage(), e);
            return "0";
        } finally {
            IOUtils.closeQuietly(instr);
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * 发送Http get请求
     *
     * @param url            请求url
     * @param isTransference 是否需要转义
     * @param requestParams  请求参数
     * @return
     */
    public static String doHttpGet(String url, boolean isTransference, String requestParams) {
        // 影像接口完整请求参数为:  http://192.168.130.105:8283/openRemoteInterface/studyList/{'empi':'16f37c30-00a0-11e3-a059-020054554e01','hospitalDomainID': '2.16.840.1.113883.4.487.2'}
        log.info("get 请求参数是: {}. url是: {}", url, requestParams);
        log.debug("get 请求参数是: {}. url是: {}", url, requestParams);

        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            getUrl(isTransference, url, requestParams);
            log.debug("影像接口添加参数后地址是: {}", url);
            // 打开和URL之间的连接
            URLConnection connection = new URL(url).openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error("调用影像接口出现异常,异常原因是: {}", e.getCause(), e);
            log.info("调用影像接口出现异常,请查看error日志.");
            return result.toString();
        } finally {
            // 使用finally块来关闭输入流
            IOUtils.closeQuietly(in);
        }
        log.debug("影像接口返回数据: {}", result);
        log.info("影像接口返回数据: {}", result);
        return result.toString();
    }

    private static void getUrl(boolean isTransference, String url, String requestParams) {
        if (!isTransference) {
            return;
        }
        try {
            url = url + requestParams
                    // 设置转义
                    .replace("{", URLEncoder.encode("{", "GBK"))
                    .replace("}", URLEncoder.encode("}", "GBK"))
                    // 替换为单引号
                    .replaceAll("\"", "\'")
                    .replaceAll(" ", "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    /**
     * @param request
     * @return
     */
    public static String getRequestUrl(HttpServletRequest request) {
        String requestUrl =
                //当前链接使用的协议
                request.getScheme()
                        //服务器地址
                        + "://" + request.getServerName()
                        //端口号
                        + ":" + request.getServerPort()
                        //应用名称，如果应用名称为
                        + request.getContextPath()
                        //请求的相对url
                        + request.getServletPath()
                        //请求参数
                        + "?" + request.getQueryString();
        return requestUrl;
    }

}
